import { PointerEvent, App, Text, IUI } from "leafer-ui";
import { ITool, IToolConfig } from "../types";
import { InnerEditorEvent } from "@leafer-in/editor";
import { isUndefined } from "@/utils/is";
export const TextTool: ITool = ({ app, config, historyUtil, box }) => {
  let text: IUI | null = null;
  // app.cursor ="move"
  const addText = (e: PointerEvent) => {
    if (text) return;
    if (app.editor.editing) return;
    const point = e.getPagePoint();
    text = Text.one(
      {
        text: "",
        editable: true,
        fill: "#FF4C26",
        fontSize: config.text.fontSize / (app.data?.fitScale ?? 1),
        editSize: "size",
        padding: 4,
      },
      point.x,
      point.y
      // 100,
      // 100
    );
    box.add(text);
    app.editor.openInnerEditor(text, true);
  };
  app.editor.on(InnerEditorEvent.CLOSE, (e: InnerEditorEvent) => {
    if (!text) return;
    if (isUndefined(text?.getAttr("text"))) {
      // app.editor.closeInnerEditor();
      // app.tree.remove(text);
    } else {
      historyUtil.commit(box.toJSON());
    }
    text = null;
  });
  const eventsMap = { [PointerEvent.DOUBLE_CLICK]: addText };
  return {
    eventsMap,
    active: () => {},
    deactive: () => {
      app.editor.closeInnerEditor();
      text = null;
    },
  };
};
